from flask import Blueprint,jsonify,request
import pdfplumber
import re,os
from datetime import datetime


wx_info_bp = Blueprint('wxinfo', __name__)
from Test import db
from config.config import Config


class WxInfo(db.Model):
    __tablename__ = 'wx_info'
    id = db.Column(db.Integer, primary_key=True)
    transactionNum = db.Column(db.String(255), nullable=True, comment='交易单号')
    tradeTime = db.Column(db.String(255), nullable=True, comment='交易时间')
    tradeType = db.Column(db.String(255), nullable=True, comment='交易类型')
    type = db.Column(db.String(255), nullable=True, comment='收/支/其他')
    payWay = db.Column(db.String(255), nullable=True, comment='交易方式')
    price = db.Column(db.String(255), nullable=True, comment='金额')
    counterparty = db.Column(db.String(255), nullable=True, comment='交易对方')
    saleOrderNum = db.Column(db.String(255), nullable=True, comment='商户单号')
    number = db.Column(db.String(255), nullable=True, comment='编号')
    name = db.Column(db.String(255), nullable=True, comment='姓名')
    identificationNumber = db.Column(db.String(255), nullable=True, comment='证件号码')
    wx_account = db.Column(db.String(255), nullable=True, comment='支付宝账号信息')
    etl_dt = db.Column(db.DateTime, default=datetime.utcnow, comment='导入时间')

@wx_info_bp.route('/getData_wxPdf', methods=['POST'])
def getData_wxPdf():
    # 设置上传文件的目录（临时目录）
    UPLOAD_FOLDER = Config.UPLOAD_FOLDER
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)

    # 检查请求中是否有文件
    if 'file' not in request.files:
        return jsonify({'data': '', 'msg': '没有文件上传', 'status': 400})

    file = request.files['file']

    # 检查文件是否有效
    if file.filename == '':
        return jsonify({'data': '', 'msg': '没有选择文件', 'status': 400})

    if file and allowed_file(file.filename):  # 确保有一个 allowed_file 函数

    # pdf_file = '/Users/wubing/Desktop/pdfData/支付宝副本.pdf'
        try:
            # 保存上传的文件
            pdf_file_path = os.path.join(UPLOAD_FOLDER, file.filename)
            file.save(pdf_file_path)
            data_list = getDataFromWxPdf(pdf_file_path)
            for data in data_list:
                db.session.add(data)
                db.session.commit()
            return jsonify({
                'data': '',
                'message': '成功导入' + len(data_list).__str__() + '条数据',
                'status': 200
            })
        except Exception as e:
            print(str(e))
            return jsonify({'data': '', 'msg': '导入数据失败，失败原因为:'+str(e),'status':500 })



def allowed_file(filename):
    ALLOWED_EXTENSIONS = {'pdf'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS




def getDataFromWxPdf(pdf_file: str) :
    # pdf_file = '/Users/wubing/Desktop/pdfData/微信支付副本.pdf'
    ##使用正则提取文本中的用户信息
    all_pages_content = ""
    with pdfplumber.open(pdf_file) as pdf:
        for page in pdf.pages:
            all_pages_content += page.extract_text()
    # 使用正则表达式匹配编号
    ##编号
    number = ''
    ##姓名
    name = ''
    ##证件号码
    identificationNumber = ''
    ##支付宝账号信息
    wx_num = ''

    pattern = r'编号：(\d+)'
    match = re.search(pattern, all_pages_content)
    if match:
        number = match.group(1)

    pattern = r'兹证明：([\u4e00-\u9fa5]+)\('
    match = re.search(pattern, all_pages_content)
    if match:
        name = match.group(1)

    pattern = r'居民身份证：(\d{6}\d{4}\d{2}\d{2}\d{3}\d{1})'
    match = re.search(pattern, all_pages_content)
    if match:
        identificationNumber = match.group(1)

    pattern = r'微信号：\s*(.*?)\s*中的'
    match = re.search(pattern, all_pages_content)
    if match:
        wx_account = match.group(1)

    with pdfplumber.open(pdf_file) as pdf:
        tables = []
        # 遍历所有的页面
        for page in pdf.pages:
            tables.extend(page.extract_tables())

    result_list = []

    for index, table_tmp in enumerate(tables):
        if index == 0:
            for index_data, table_data in enumerate(table_tmp):
                if index_data > 2:
                    object = get_object(table_data,number,name,identificationNumber,wx_account)
                    result_list.append(object)
        else:
           for index_data,table_data in enumerate(table_tmp):
               object = get_object(table_data, number, name, identificationNumber, wx_account)
               result_list.append(object)
    return result_list

def get_object(table_data,number,name,identificationNumber,wx_account) ->WxInfo:
    transactionNum = table_data[0].replace('\n', '')
    tradeTime = table_data[1].replace('\n', ' ')
    tradeType = table_data[2].replace('\n', '')
    type = table_data[3].replace('\n', '')
    payWay = table_data[4].replace('\n', '')
    price = table_data[5].replace('\n', '')
    counterparty = table_data[6].replace('\n', '')
    saleOrderNum = table_data[7].replace('\n', ' ')

    object = WxInfo()
    object.transactionNum = transactionNum
    object.tradeTime = tradeTime
    object.tradeType = tradeType
    object.type = type
    object.payWay = payWay
    object.price = price
    object.counterparty = counterparty
    object.saleOrderNum = saleOrderNum
    object.number = number
    object.name = name
    object.identificationNumber = identificationNumber
    object.wx_account = wx_account
    return object
